package cn.yuhh.dao.impl;

import cn.yuhh.dao.IFoodTypeDao;
import cn.yuhh.entity.FoodType;
import cn.yuhh.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by Brill on 2016/12/9.
 */
public class FoodTypeDao implements IFoodTypeDao {

    private QueryRunner qr = JdbcUtils.getQuerrRunner();

    @Override
    public void add(FoodType foodType) {
        String sql = "INSERT into foodtype(typeName) VALUES(?)";
        try {
            qr.update(sql, foodType.getTypeName());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(int id) {
        String sql = "delete from foodtype where id=?";
        try {
            qr.update(sql, id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(FoodType ft) {
        String sql = "update foodtype set typeName=? where id=?";
        try {
            qr.update(sql, ft.getTypeName(), ft.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<FoodType> query() {
        String sql = "select * from foodtype";
        try {
            return qr.query(sql, new BeanListHandler<FoodType>(FoodType.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public FoodType findById(int id) {
        String sql = "SELECT * FROM foodtype WHERE id=?";
        try {
            return qr.query(sql, new BeanHandler<FoodType>(FoodType.class), id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<FoodType> query(String keyword)
    {
        String sql = "select * from foodtype where typeName like ?";
        try {
            return qr.query(sql, new BeanListHandler<FoodType>(FoodType.class), "%" + keyword + "%");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Integer getFistType() {

        return null;
    }

    @Test
    public void queryTest() {
        List<FoodType> types = query();
        for (FoodType type :
                types) {
            System.out.println(type);
        }
    }

    @Test
    public void queryTest2() {
        List<FoodType> types = query("四");
        for (FoodType type :
                types) {
            System.out.println(type);
        }
    }

    @Test
    public void queryTest3() {
        FoodType foodType = findById(2);
        System.out.println(foodType);

    }
}
